#include "head.h"


void conceal(char* password);
// 登录
int login(me_t* me, int sock_fd)
{

    me_t tmp_me;
    bzero(&tmp_me, sizeof(tmp_me));
    fprintf(stderr, "请输入用户名:");
    fscanf(stdin, "%s", tmp_me.name); 
    messenger_t msg;
    bzero(&msg, sizeof(msg));

    fprintf(stderr, "请输入密码:");
    conceal(msg.args);
    printf("\n");
    // 拼接参数
    strcat(msg.args, "&");
    strcat(msg.args, tmp_me.name);

    // 修改请求类型
    msg.cmd = LOGIN;

    // 验证用户名和密码
    send(sock_fd, &msg, sizeof(msg), MSG_NOSIGNAL);
    char reply[10] = {0};
    recv(sock_fd, reply, 8, 0);
    printf("reply: %s\n",reply);
    if(strcmp("succeedd", reply) == 0)
    {
        // 成功
        char jwt[1024] = {0};
        size_t jwt_lenth = 0;
        recv(sock_fd, &jwt_lenth, sizeof(size_t), MSG_WAITALL);
        recv(sock_fd, &jwt, jwt_lenth, MSG_WAITALL);
        printf("%ld: %s\n", jwt_lenth, jwt);
        sprintf(tmp_me.token, "%s", jwt);
        sprintf(tmp_me.path, "/");
        tmp_me.login = true;
        *me = tmp_me;
        printf("登陆成功\n");
    }
    else if(strcmp("username", reply) == 0)
        printf("用户不存在\n");
    else if(strcmp("faileded", reply) == 0)
        printf("密码错误\n");
    
    return 0;
}

// 注册
int register_(me_t* me, int sock_fd)
{
    me_t tmp_me;
    bzero(&tmp_me, sizeof(tmp_me));
    fprintf(stderr, "请输入用户名:");
    fscanf(stdin, "%s", tmp_me.name); 

    messenger_t msg;
    bzero(&msg, sizeof(msg));

    fprintf(stderr, "请输入密码:");
    conceal(msg.args);
    printf("\n");
    
    // 拼接参数
    strcat(msg.args, "&");
    strcat(msg.args, tmp_me.name);

    // 修改请求类型
    msg.cmd = REGISTER;

    // 验证用户是否存在
    send(sock_fd, &msg, sizeof(msg), MSG_NOSIGNAL);
    char reply[10] = {0};
    recv(sock_fd, reply, sizeof(reply), 0);
    printf("reply: %s\n",reply);
    if(strcmp("succeed", reply) == 0)
    {
        strcat(tmp_me.path, "/");
        tmp_me.login = true;
        *me = tmp_me;
        printf("注册成功, 已登录\n");
    }
    else
        printf("用户存在\n");

    return 0;
}

// 隐藏密码
void conceal(char* password)
{
    struct termios oldt, newt;

    // 获取终端属性
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;

    // 关闭回显模式
    newt.c_lflag &= ~(ECHO);

    // 设置新的终端属性
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    // 读取密码
    fscanf(stdin, "%s", password);

    // 恢复终端属性
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
}